var block_type = [];
$(function () {
});
layui.use(['element','table','layer','form'], function(){
	var table = layui.table;
	var layer = layui.layer;
	var form=layui.form
		, $ = layui.jquery;
	util = layui.util;

	table.render({
		elem: '#basicRoomTable',
		height: 'full-150',
		url:  "/basicRoom/roomTable", //数据接口
		method: 'post',
		request:{
			page: 'pageNum', //页码的参数名称，默认：page
			limit: 'pageSize' //每页数据量的参数名，默认：limit
		},
		where: {
			searchName: "",
			community: $(window.parent.document).find("#community").val()
		},
		page: true, //开启分页
		cols: [[ //表头
			{type:'numbers'}
			,{field: 'roomId', title: '房间ID',width:180,align:'center' }
			,{field: 'roomName', title: '房间号',width:120,sort: true,align:'center' 	}
			,{field: 'roomDesc', title: '描述',width:120,align:'center' }
			,{field: 'blockId', title: '楼栋ID',width:180, align:'center' }
			,{field: 'blockName', title: '楼层名称',width:120, align:'center'  }
			,{field: 'createTime', title: '添加时间',width:170, align:'center',sort: true,templet: function (d) {
					return util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss");
				}    }
			, {field: 'right', title: '操作', align:'center',width:200,templet:function(data){
					var op = '<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>';
					op+='<a class="layui-btn layui-btn-xs" lay-event="delete">删除</a>';
					return op;
				}
			}
		]]

	});
	function loadBlockOptions(){
		$.ajax({
			url: "/basicBlock/selBlockList",
			data: {community:$(window.parent.document).find("#community").val()},
			dataType: 'json',
			type: 'post',
			async:false,
			success: function(data){
				if(data.resultCode === '000'){
					var content = data.resultContent;
					var com_html = "<option value=\"\" selected=\"\" >--请选择--</option>";
					for(var i in content){
						com_html += '<option value="'+ content[i].blockId +'"  > '+content[i].blockName +' </option>';
						block_type[content[i].blockId] = content[i].blockName;
					}
					$('#blockId').html(com_html);
				}
			},
			error : function(){
				alert('获取楼栋信息失败');
			}
		});
	}
	//添加房间信息
	addRoom = function () {
		loadBlockOptions();
		$("#basic_up_room").hide();
		$("#basic_form_room").show();
		$("#basic_form_room").attr("disabled", false);
		$("#basic_form_room").attr("class", "layui-btn");
		$("#product_form_room")[0].reset();
		layer.open({
			type: 1
			, title: '新增'
			, shadeClose: true
			, area: ['500px', '80%']
			, content: $('#roomAdd')
		});
	};

	//操作列
	table.on('tool(basicRoomTable)', function(obj){
		var data = obj.data;
		if(obj.event === 'delete'){
			layer.confirm('是否确认删除'+data.roomName+'的信息？', {
				btn: ['确认', '返回'] //按钮
			}, function () {
				var index = layer.load(2, {
					shade: [0.4, '#000'],
					content: '提交中...',
					success: function (layero) {
						layero.find('.layui-layer-content').css({
							'padding-top': '40px',
							'width': '200px'
						});
					}
				});
				var companyId = $(window.parent.document).find("#community").val();
				var code = $(window.parent.document).find("#community option:selected").attr("id");
				$.post('/basicRoom/delRoom',
					{bid:data.roomId,companyId:companyId,blockId:data.blockId,code:code},
					function (res) {
					if(res.resultCode === '000'){
						layer.msg('删除成功',{
							time:500,
							end:function () {
								reloadRoomList();
							}
						})
					}else{
						layer.msg(res.resultDesc);
					}
					layer.close(index);
				})
			})
		}else if (obj.event === 'edit'){
			loadBlockOptions();
			$("#basic_up_room").show();
			$("#basic_form_room").hide();
			$("#basic_up_room").attr("disabled", false);
			$("#basic_up_room").attr("class", "layui-btn");
			form.val('product_form_room',{
				'roomId': data.roomId,
				'roomName': data.roomName,
				'roomDesc':data.roomDesc,
				'blockId':data.blockId,
				'blockName': data.blockName,
			});
			$("#blockName").val(data.blockName);//隐藏的标签需要这样设置
			if(!data.blockName){ //blockName为空
				var bName = $("#blockId").find("option:selected").text();
				$("#blockName").val(bName);
			}
			form.render();
			layer.open({
				type: 1
				, title: '编辑信息'
				, shadeClose: true
				, area: ['500px', '80%']
				, content: $('#roomAdd')
			});
		}
	});

	//提交房间信息表单
	form.on('submit(basic_form_room)',function(data){
		$("#basic_form_room").attr("disabled", true);
		$("#basic_form_room").attr("class", "layui-btn layui-btn-disabled");
		var inFun = 0;
		layer.confirm('是否确认提交房间信息？', {
			btn: ['确认', '返回'] //按钮
		}, function () {
			if(inFun === 1){
				return;
			}
			inFun = 1;
			data.field.companyId = $(window.parent.document).find("#community").val();
			data.field.housingEstateId = $(window.parent.document).find("#community option:selected").attr("id");
			var index = layer.load(2, {
				shade: [0.4, '#000'],
				content: '提交中...',
				success: function (layero) {
					layero.find('.layui-layer-content').css({
						'padding-top': '40px',
						'width': '200px'
					});
				}
			});
			$.post("/basicRoom/addRoom", data.field, function (data) {
				if(data.resultCode === "000"){
					layer.closeAll();
					layer.msg('提交成功',{
						time:500,
						end:function () {
							reloadRoomList();
						}
					})
				}else{
					layer.close(index);
					layer.msg( data.resultDesc );
					$("#basic_form_room").attr("disabled", false);
					$("#basic_form_room").attr("class", "layui-btn");
				}
			})
		}, function () {
			layer.closeAll();
			$("#basic_form_room").attr("disabled", false);
			$("#basic_form_room").attr("class", "layui-btn");
			return false;
		});
		return false;//返回false 防止二次提交
	});

	//更新房间信息
	form.on('submit(basic_up_room)',function(data){
		$("#basic_up_room").attr("disabled", true);
		$("#basic_up_room").attr("class", "layui-btn layui-btn-disabled");
		var inFun = 0;
		layer.confirm('是否确认更新房间信息？', {
			btn: ['确认', '返回'] //按钮
		}, function () {
			if(inFun === 1){
				return;
			}
			inFun = 1;
			var index = layer.load(2, {
				shade: [0.4, '#000'],
				content: '提交中...',
				success: function (layero) {
					layero.find('.layui-layer-content').css({
						'padding-top': '40px',
						'width': '200px'
					});
				}
			});
			data.field.companyId = $(window.parent.document).find("#community").val();
			data.field.housingEstateId = $(window.parent.document).find("#community option:selected").attr("id");
			$.post("/basicRoom/upRoom", data.field, function (data) {
				if(data.resultCode === "000"){
					layer.closeAll();
					layer.msg('更新成功',{
						time:500,
						end:function () {
							reloadRoomList();
						}
					})
				}else{
					layer.close(index);
					layer.msg( data.resultDesc );
					$("#basic_up_room").attr("disabled", false);
					$("#basic_up_room").attr("class", "layui-btn");
				}
			})
		}, function () {
			layer.closeAll();
			return false;
			$("#basic_up_room").attr("disabled", false);
			$("#basic_up_room").attr("class", "layui-btn");
		});
		return false;//返回false 防止二次提交
	});

	//查询房间
	function reloadRoomList(){
		var name = $.trim($('#searchName').val());
		var blockId = $.trim($('#blockIdSearch').val());
		var blockName = $.trim($('#blockNameSearch').val());
		//执行重载
		table.reload('basicRoomTable', {
			page: {
				curr: 1 //重新从第 1 页开始
			}
			,where: {
				roomName: name,
				community: $(window.parent.document).find("#community").val(),
				blockId:blockId, blockName:blockName
			}
		});
	}
	form.on('submit(search_room)',function () {
		//执行重载
		reloadRoomList();
		return false;
	});

	//检测blockId 选择的变化
	form.on('select(blockId)', function (data) {
		$('#blockName').val(block_type[data.value]);
	});

	// 同步数据
	$("#sync").on('click', function (){
		layer.confirm('同步数据耗时较长，是否继续？', {
			btn: ['确认', '取消'] //按钮
		}, function () {
			var index = layer.load(2, {
				shade: [0.4, '#000'],
				content: '同步中...',
				success: function (layero) {
					layero.find('.layui-layer-content').css({
						'padding-top': '40px',
						'width': '200px'
					});
				}
			});
			var companyId = $(window.parent.document).find("#community").val();
			$.post('/basicRoom/syncData',{companyId:companyId},function (res) {
				if(res.resultCode === '000'){
					layer.msg(res.resultDesc,{
						time:500,
						end:function () {
							reloadRoomList();
						}
					})
				}else{
					layer.msg(res.resultDesc);
				}
				layer.close(index);
			});
		})
	});
	// 导入
	$("#import").on('click', function (){
		layer.open({
			type: 1
			,title: '上传文件'
			,area: ['45%','30%']
			,content: $('#upload')
		});
	});

	// 导出
	$("#exportAll").on('click', function (){
		var communityId = $(window.parent.document).find("#community").val();
		if(communityId === ""){
			return layer.msg("小区id为空!",{icon:5});
		}
		downloadFile("/basicRoom/exportRoom2Excel?communityId="+communityId);
	});

	// 下载模板
	$("#down_room_template").on('click', function (){
		$('#downButton')[0].click();
	});
	//提交导入信息
	form.on('submit(upload_form)',function(){
		$("#upload_form").attr("disabled", true);
		$("#upload_form").attr("class", "layui-btn layui-btn-disabled");
		var formData = new FormData();
		formData.append("file",$("#uploadExcel")[0].files[0]);
		formData.append("community",$(window.parent.document).find("#community").val());
		formData.append("housingEstateId",$(window.parent.document).find("#community option:selected").attr("id"));
		layer.load();
		$.ajax({
			url:'/basicRoom/uploadRoom',
			type: 'POST',
			data: formData,
			processData: false,
			contentType:false,
			success:function(res){
				if (res.resultCode === "000") {
					reloadRoom();
					layer.msg('导入成功!',{icon: 1});
				}else {
					layer.msg(res.resultDesc,{
						time:5000,
					})
				}
				setTimeout(function () {
					layer.closeAll();
				},1000);
				$("#uploadExcel").val("");
				$("#file_name").val("");
				$("#upload_form").attr("disabled", false);
				$("#upload_form").attr("class", "layui-btn");
			}

		});
		return false;
	});

	$("#uploadProductBtn").on("click",function(){
		$("#uploadExcel").click();
	});
	$("#uploadExcel").on("change",function(){
		var name = $("#uploadExcel").val();
		var fileType = name.substring(name.lastIndexOf(".")+1);
		if(fileType !== "xls" && fileType !== "xlsx"){
			layer.msg("亲，请选择正确的excel格式哦!",{icon:5});
			$("#upload_form").attr("disabled", true);
			$("#upload_form").addClass("layui-btn-disabled");
		}else {
			$("#upload_form").attr("disabled", false);
			$("#upload_form").removeClass("layui-btn-disabled");
			var index = name.lastIndexOf("\\")+1;
			$("#file_name").val(name.substring(index));
		}
	});

})

function reloadRoom(){
	location.reload();
}